(function(angular) {
    "use strict";

    var ctl_module = angular.module("cloapCertificateApp.controller");

    ctl_module.controller("organ_control.listCtl", function($scope, $modal,
            OrganControl, Organ, CheckOrgan) {
        var modal_instance = null;

        $scope.organ_controls = OrganControl.query();
        $scope.widget_title = "机构控管";

        $scope.editOrAdd = function(operate, organ_control_id) {
            $scope.organs = Organ.all();
            $scope.check_organs = CheckOrgan.query();

            var ctl = isAdd(operate) ? "organ_control.addCtl" : "organ_control.editCtl";

            modal_instance = $modal.open({
                scope: $scope,
                templateUrl: "/cloap/app/cloapCertificateApp/partials/organ_control_form.html",
                controller: ctl,
                resolve: {
                    params: function() {
                        return {
                            organ_control_id: organ_control_id
                        };
                    }
                }
            });

            function isAdd(operate) {
                return operate === "add";
            }
        };

        $scope.saveOrganControl = function(save_method, data, callback) {
            OrganControl[save_method](data, callback, function(response) {
                alert(response.message || "保存失败");
            });
        };

        $scope.deleteOrganControl = function(organ_control_id) {
            OrganControl.delete({organ_control_id: organ_control_id}, function() {
                $scope.$emit("change_organ_control");
            });
        };

        $scope.$on("change_organ_control", function() {
            $scope.organ_controls = OrganControl.query();
        });

        $scope.closeModal = function() {
            modal_instance.close();
        };
    });

    ctl_module.controller("organ_control.editCtl", function($scope, OrganControl, params) {
        var save_method = "update";

        $scope.organ_control = OrganControl.get({organ_control_id: params.organ_control_id});
        $scope.widget_title = "编辑机构管控";

        $scope.save = function() {
            $scope.saveOrganControl(save_method, $scope.organ_control, saveSuccessCallBack);
        };

        function saveSuccessCallBack() {
            $scope.$emit("change_organ_control");
            $scope.closeModal();
        }
    });

    ctl_module.controller("organ_control.addCtl", function($scope) {
        var save_method = "save";
        $scope.organ_control = {};
        $scope.widget_title = "添加机构管控";

        $scope.save = function() {
            $scope.saveOrganControl(save_method, $scope.organ_control, saveSuccessCallBack);
        };

        function saveSuccessCallBack() {
            $scope.$emit("change_organ_control");
            $scope.closeModal();
        }
    });

}(angular));
